import { fetchJson } from '@/lib/utils/server';
import { ResultDto } from '@/types/response/common';
import { ChannelDetail } from '@/types/channel';
import { notFound, permanentRedirect } from 'next/navigation';
import { buildWatchUrl } from '@/lib/utils/channel';
import WatchView from './WatchView';

type Props = {
	params: Promise<{ identifier: string }>;
};

export default async function WatchPage({ params }: Props) {
	const { identifier } = await params;
	const decoded = decodeURIComponent(identifier);
	const res: ResultDto<ChannelDetail> = await fetchJson(`/api/channel/${encodeURIComponent(decoded)}`, { method: 'GET' });

	if (!res.data) {
		notFound();
	}

	const canonical = buildWatchUrl(res.data);
	const current = `/watch/${decoded}`;
	if (current !== canonical) {
		permanentRedirect(canonical);
	}

	return <WatchView channel={res.data} />;
}